package study.sharding.shardingjdbc.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import study.sharding.shardingjdbc.mapper.user.UserBaseEO;
import study.sharding.shardingjdbc.mapper.user.UserBaseMapper;

@Slf4j
@Service
public class UserService {

    private static final Long SEQ = 3000L;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Transactional
    public void add_01() {
        for (int i = 1; i <= 5; i++) {
            Long userId = SEQ + i;

            if (i == 4) {
                throw new RuntimeException("我是业务异常");
            }

            UserBaseEO ubEO = new UserBaseEO();
            ubEO.setUbUserId(userId);
            ubEO.setUbLoginName("wangwu");
            ubEO.setUbLoginPwd("123123");
            userBaseMapper.insert(ubEO);
        }
    }


    @Transactional
    @ShardingTransactionType(TransactionType.XA)
    public void add_02() {
        for (int i = 1; i <= 5; i++) {
            Long userId = SEQ + i;

            if (i == 4) {
                throw new RuntimeException("我是业务异常");
            }

            UserBaseEO ubEO = new UserBaseEO();
            ubEO.setUbUserId(userId);
            ubEO.setUbLoginName("wangwu");
            ubEO.setUbLoginPwd("123123");
            userBaseMapper.insert(ubEO);
        }
    }

    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void add_03() {
        for (int i = 1; i <= 5; i++) {
            Long userId = SEQ + i;

            if (i == 4) {
                throw new RuntimeException("我是业务异常");
            }

            UserBaseEO ubEO = new UserBaseEO();
            ubEO.setUbUserId(userId);
            ubEO.setUbLoginName("wangwu");
            ubEO.setUbLoginPwd("123123");
            userBaseMapper.insert(ubEO);
        }
    }
}
